<!-- 客户列表页面 -->
<template>
  <s-layout title="我的档案" :bgStyle="{ color: '#FFF' }">
    <!-- 客户列表 -->
    <view v-if="state.pagination.list.length > 0" class="customer-list">
      <view v-for="(customer, index) in state.pagination.list" :key="customer.id" class="customer-item"
            @click="goToDetail(customer.id)">
        <!-- 客户基本信息 -->
        <view class="customer-info">
          <view class="customer-header">
            <view class="customer-name">{{ customer.customerName }}</view>
            <view class="customer-gender" v-if="customer.gender">
              <text class="gender-tag" :class="getGenderClass(customer.gender)">
                {{ getGenderLabel(customer.gender) }}
              </text>
            </view>
          </view>

          <view class="customer-details">
            <view class="detail-item" v-if="customer.contactPhone">
              <uni-icons type="phone" size="14" color="#666" />
              <text class="detail-text">{{ customer.contactPhone }}</text>
            </view>
            <view class="detail-item" v-if="customer.age">
              <uni-icons type="person" size="14" color="#666" />
              <text class="detail-text">{{ customer.age }}岁</text>
            </view>
            <view class="detail-item" v-if="customer.remainingCount !== null">
              <uni-icons type="calendar" size="14" color="#666" />
              <text class="detail-text">剩余{{ customer.remainingCount }}次</text>
            </view>
          </view>

          <view class="customer-status" v-if="customer.healthStatus">
            <uni-icons type="location" size="14" color="#666" />
            <text class="status-text">{{ customer.healthStatus }}</text>
          </view>
          <view class="customer-status" v-if="customer.creatorName" @click.stop="callPhone(customer.agentPhone)">
            <uni-icons type="chatboxes" size="14" color="#666" />
            <text class="status-text">{{ customer.creatorName }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="!state.loading && state.pagination.list.length === 0" class="empty-state">
      <uni-icons type="folder-add" size="60" color="#ccc" />
      <view class="empty-text">暂无档案</view>
      <view class="empty-desc">点击下方按钮，立即新增您的第一份档案</view>
    </view>

    <!-- 加载状态 -->
    <uni-load-more v-if="state.pagination.list.length > 0" :status="state.loadStatus" :content-text="loadText"
                   @clickLoadMore="loadData" />

    <!-- 新增客户按钮 -->
    <view class="add-customer-btn" @click="addCustomer" v-if="state.pagination.list.length===0">
      <uni-icons type="plusempty" size="30" color="#fff" />
    </view>

  </s-layout>
</template>

<script setup>
  import {
    onLoad,
    onShow,
    onPullDownRefresh,
    onReachBottom
  } from '@dcloudio/uni-app';
  import {
    reactive,
    computed
  } from 'vue';
  import CustomerApi from '@/sheep/api/customer/customer';
  import DictApi from '@/sheep/api/system/dict';
  import {
    resetPagination
  } from '@/sheep/helper/utils';

  const state = reactive({
    searchKeyword: '',
    loading: false,
    loadStatus: '',
    genderOptions: [],
    pagination: {
      list: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
    },
  });

  // 加载状态文本
  const loadText = computed(() => {
    return {
      contentdown: '上拉显示更多',
      contentrefresh: '正在加载...',
      contentnomore: '没有更多数据了'
    };
  });

  async function callPhone(tel) {
    uni.makePhoneCall({
      phoneNumber: tel // 替换为你要拨打的号码
    });
  }

  // 获取性别字典数据
  async function getGenderOptions() {
    try {
      let {
        code,
        data
      } = await DictApi.getDictDataListByType('system_user_sex');
      if (code === 0 && data) {
        state.genderOptions = data;
      }
    } catch (error) {
      console.error('获取性别字典失败:', error);
    }
  }

  // 获取客户列表
  async function getCustomerList() {
    if (state.loadStatus === 'loading') return;

    state.loadStatus = 'loading';
    state.loading = state.pagination.pageNo === 1;

    try {
      let {
        code,
        data
      } = await CustomerApi.getMyCustomerPage({
        pageNo: state.pagination.pageNo,
        pageSize: state.pagination.pageSize,
        customerName: state.searchKeyword || undefined,
      });

      if (code !== 0) {
        throw new Error('获取客户列表失败');
      }

      if (state.pagination.pageNo === 1) {
        state.pagination.list = data.list;
      } else {
        state.pagination.list = state.pagination.list.concat(data.list);
      }

      state.pagination.total = data.total;
      state.loadStatus = state.pagination.list.length < state.pagination.total ? 'more' : 'noMore';

    } catch (error) {
      console.error('获取客户列表失败:', error);
      state.loadStatus = 'noMore';

      if (state.pagination.pageNo === 1) {
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'error'
        });
      }
    } finally {
      state.loading = false;
    }
  }

  // 加载更多数据
  function loadData() {
    if (state.loadStatus === 'loading') return;

    state.pagination.pageNo++;
    getCustomerList();
  }

  // 搜索输入
  function onSearchInput(e) {
    state.searchKeyword = e.detail.value;
  }

  // 搜索确认
  function onSearchConfirm() {
    resetPagination(state.pagination);
    getCustomerList();
  }

  // 清除搜索
  function clearSearch() {
    state.searchKeyword = '';
    resetPagination(state.pagination);
    getCustomerList();
  }

  // 获取性别标签
  function getGenderLabel(gender) {
    const option = state.genderOptions.find(item => item.value === gender);
    return option ? option.label : gender;
  }

  // 获取性别样式类
  function getGenderClass(gender) {
    return {
      'gender-male': gender === 'MALE',
      'gender-female': gender === 'FEMALE',
      'gender-unknown': gender === 'UNKNOWN'
    };
  }

  // 跳转到客户详情
  function goToDetail(customerId) {
    uni.navigateTo({
      url: `/pages/customer/form/index?id=${customerId}&mode=view`
    });
  }

  // 添加客户
  function addCustomer() {
    uni.navigateTo({
      url: '/pages/customer/form/index?mode=add'
    });
  }

  // 编辑客户
  function editCustomer(customerId) {
    uni.navigateTo({
      url: `/pages/customer/form/index?id=${customerId}&mode=edit`
    });
  }

  // 删除客户
  function deleteCustomer(customerId) {
    uni.showModal({
      title: '确认删除',
      content: '确定要删除这个客户吗？删除后无法恢复。',
      success: async (res) => {
        if (res.confirm) {
          try {
            let {
              code
            } = await CustomerApi.deleteCustomer({
              id: customerId
            });
            if (code === 0) {
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });

              // 重新加载列表
              resetPagination(state.pagination);
              getCustomerList();
            } else {
              throw new Error('删除失败');
            }
          } catch (error) {
            console.error('删除客户失败:', error);
            uni.showToast({
              title: '删除失败',
              icon: 'error'
            });
          }
        }
      }
    });
  }

  // 页面加载
  onLoad((options) => {
    // getGenderOptions();
    // getCustomerList();
  });
  onShow(() => {
    getGenderOptions();
    resetPagination(state.pagination);
    getCustomerList();
  });

  // 下拉刷新
  onPullDownRefresh(() => {
    resetPagination(state.pagination);
    getCustomerList().then(() => {
      uni.stopPullDownRefresh();
    });
  });

  // 上拉加载更多
  onReachBottom(() => {
    if (state.loadStatus === 'more') {
      loadData();
    }
  });
</script>

<style lang="scss" scoped>
  .search-container {
    padding: 20rpx;
    background: #fff;
    border-bottom: 2rpx solid #f0f0f0;
  }

  .search-box {
    display: flex;
    align-items: center;
    background: #f8f9fa;
    border-radius: 50rpx;
    padding: 20rpx 30rpx;
    gap: 20rpx;
  }

  .search-input {
    flex: 1;
    font-size: 28rpx;
    color: #333;

    &::placeholder {
      color: #999;
    }
  }

  .clear-btn {
    padding: 10rpx;

    &:active {
      opacity: 0.6;
    }
  }

  .customer-list {
    padding: 20rpx;
  }

  .customer-item {
    display: flex;
    background: #fff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
      opacity: 0.8;
    }
  }

  .customer-info {
    flex: 1;
  }

  .customer-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    gap: 20rpx;
  }

  .customer-name {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }

  .customer-gender {
    .gender-tag {
      font-size: 22rpx;
      padding: 6rpx 12rpx;
      border-radius: 20rpx;
      color: #fff;

      &.gender-male {
        background: #007aff;
      }

      &.gender-female {
        background: #ff3b30;
      }

      &.gender-unknown {
        background: #999;
      }
    }
  }

  .customer-details {
    display: flex;
    flex-direction: column;
    gap: 12rpx;
    margin-bottom: 20rpx;
  }

  .detail-item {
    display: flex;
    align-items: center;
    gap: 12rpx;
  }

  .detail-text {
    font-size: 26rpx;
    color: #666;
  }

  .customer-status {
    .status-text {
      font-size: 24rpx;
      color: #999;
      // background: #f8f9fa;
      padding: 8rpx 16rpx;
      // border-radius: 20rpx;
      display: inline-block;
    }
  }

  .customer-actions {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    margin-left: 20rpx;
  }

  .action-btn {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;

    &.edit-btn {
      background: rgba(0, 122, 255, 0.1);

      &:active {
        background: rgba(0, 122, 255, 0.2);
      }
    }

    &.delete-btn {
      background: rgba(255, 59, 48, 0.1);

      &:active {
        background: rgba(255, 59, 48, 0.2);
      }
    }
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 40rpx;
    text-align: center;
  }

  .empty-text {
    font-size: 32rpx;
    color: #666;
    margin: 30rpx 0 16rpx 0;
  }

  .empty-desc {
    font-size: 26rpx;
    color: #999;
  }

  .add-customer-btn {
    position: fixed;
    right: 40rpx;
    bottom: 100rpx;
    width: 100rpx;
    height: 100rpx;
    background: #007aff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 20rpx rgba(0, 122, 255, 0.3);
    z-index: 999;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.9);
    }
  }

  /* 加载更多样式 */
  :deep(.uni-load-more) {
    padding: 30rpx 0;
  }
</style>
